﻿using System;
using System.Collections.Generic;
using System.Linq;
using Missbot.Common;
using Missbot.Core.Base;
using Missbot.Core.Cache;
using Missbot.Model.MsgCmds.Drive;
using Missbot.Model.MsgInfos;

namespace Missbot.Core.Common
{
    public class FileUploader
    {
        #region Svcs

        private static ChannelMgr ChannelMgr => AutofacSvc.Resolve<ChannelMgr>();
        private static ILogSvc ILogSvc => AutofacSvc.Resolve<ILogSvc>();

        #endregion

        public static InstanceFile PicUpload(string FolderID, string Url, bool IsSensitive = false)
        {
            var marker = Guid.NewGuid().ToString("N");
            MsgSender.PushMsgDelay(new UploadUrlCmd { FolderID = FolderID, URL = Url, Marker = marker, IsSensitive = IsSensitive }, 1);
            var uploadFinish = ChannelMgr.Wait("UrlUploadFinished", info => info.Addition.GetString("Marker") == marker, 100);
            if (uploadFinish == null)
            {
                ILogSvc.Log($"Pic Upload faild. FolderID: {FolderID}; Url: {Url}");
                return null;
            }

            return uploadFinish.Files.First();
        }

        public static IEnumerable<InstanceFile> PicUpload(string FolderID, List<string> Urls, bool IsSensitive = false)
        {
            var markers = new List<string>();
            foreach (var url in Urls)
            {
                var marker = Guid.NewGuid().ToString("N");
                markers.Add(marker);
                MsgSender.PushMsgDelay(new UploadUrlCmd { FolderID = FolderID, URL = url, Marker = marker, IsSensitive = IsSensitive }, 1);
            }

            var finish = ChannelMgr.Wait("UrlUploadFinished",
                                         markers.Select(marker => new Predicate<InboxSession>(info => info.Addition.GetString("Marker") == marker)).ToList(),
                                         100);
            if (finish == null)
            {
                ILogSvc.Log($"Pic Upload faild. FolderID: {FolderID}; Urls: {string.Join(",", Urls)}");
                return null;
            }

            return finish.Select(f => f.Files.First());
        }
    }
}